package com.backend.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.common.constant.RedisConstant;
import com.common.threadlocal.UserLocal;
import com.pojo.dto.UserDTO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RefreshTokenInterceptor implements HandlerInterceptor {
    StringRedisTemplate stringRedisTemplate;
    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uuid = request.getHeader("Authorization");
        if (StrUtil.isBlank(uuid)) {
            log.info("请求中未携带,无token");
            return true;
        }
        String token = RedisConstant.LOGIN_USER_KEY + uuid;
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(token);
        if (entries.isEmpty()) {
            log.info("redis该token已失效");
            return true;
        }
        UserDTO userDTO = BeanUtil.fillBeanWithMap(entries, new UserDTO(), false);
        UserLocal.setCurrentUserDTO(userDTO);
        stringRedisTemplate.expire(token, RedisConstant.LOGIN_USER_TTL, TimeUnit.MINUTES);
        return true;
    }
}